package org.maxl.util;

import com.google.common.base.Preconditions;

import javax.annotation.Nonnull;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2017/3/16.
 */
public class MBeanExporters {
    private static final Logger logger = Logger.getLogger(MBeanExporters.class.getName());
    public static final String UTIL_JMX_ENABLED = "util.jmx.enabled";
    public static final String UTIL_JMX_DEFAULT = "false";

    public MBeanExporters() {
    }

    public static void registerBean(@Nonnull Object bean) {
        Preconditions.checkNotNull(bean);

        try {
            MBeanServer e = ManagementFactory.getPlatformMBeanServer();
            Class clazz = bean.getClass();
            ObjectName objectName = new ObjectName(clazz.getPackage().getName() + ":name=" + clazz.getSimpleName());
            if(!e.isRegistered(objectName)) {
                e.registerMBean(bean, objectName);
            } else {
                logger.log(Level.WARNING, String.format("The bean[%s] has bean registered in JMX Server.", new Object[]{bean.getClass().getName()}));
            }
        } catch (Exception var4) {
            logger.log(Level.WARNING, "MBeanExporters ERROR", var4);
        }

    }

    public static void registerBean(@Nonnull String name, @Nonnull Object bean) {
        Preconditions.checkNotNull(bean);
        Preconditions.checkNotNull(name);

        try {
            MBeanServer e = ManagementFactory.getPlatformMBeanServer();
            Class clazz = bean.getClass();
            ObjectName objectName = new ObjectName(clazz.getPackage().getName() + ":name=" + name);
            if(!e.isRegistered(objectName)) {
                e.registerMBean(bean, objectName);
            } else {
                logger.log(Level.WARNING, String.format("The bean[%s] has bean registered in JMX Server.", new Object[]{bean.getClass().getName() + "#" + name}));
            }
        } catch (Exception var5) {
            logger.log(Level.WARNING, "MBeanExporters ERROR", var5);
        }

    }
}
